import 'package:flutter/material.dart';
import 'package:we_chat/pages/chat/search_bar.dart';
import 'package:we_chat/pages/chat/chat_page.dart';

class SearchPage extends StatefulWidget {
  final List<Chat>? datas;
  SearchPage({this.datas});

  @override
  State<SearchPage> createState() => _SearchPageState();
}

class _SearchPageState extends State<SearchPage> {
  List<Chat> _models = [];
  String _searchStr = '';
  TextStyle _normalStyle = TextStyle(
    fontSize: 16,
    color: Colors.black
  );
  TextStyle _hightLightStyle = TextStyle(
      fontSize: 16,
      color: Colors.green
  );

  Widget _title(String text){
    List<TextSpan> spans = [];
    //默认有一个，连续两个空串代表有三个，有个空串代表有两个，没有空串有分离就代表有一个
    List<String> strs = text.split(_searchStr);
    // print('strs:$strs');

    for(int i=0;i<strs.length;i++){
      String str = strs[i];

      //空串&&也不是最后一个，连续的才有空串
      if(str == '' && i<str.length-1){
        spans.add(TextSpan(text: _searchStr,style: _hightLightStyle));//增加高亮

      } else {//不连续的，才没有空串
        spans.add(TextSpan(text: str,style: _normalStyle));

        if(i<strs.length-1){//不是最后一个字符
          spans.add(TextSpan(text: _searchStr,style: _hightLightStyle));//增加高亮
        }
      }

    }


    return RichText(text: TextSpan(children:spans));
  }

  void _searchData(String text) {
    _searchStr = text;
    //清空
    _models.clear();
    // print('datas:${widget.datas}');
    if(text.length > 0 && widget.datas!=null){
      for(int i=0; i<widget.datas!.length;i++){
        Chat model = widget.datas![i];
        if(model.name.contains(text)){
          _models.add(model);
          // print('name: ${model.name}');
        }
      }
    }
    // print('_models:$_models');
    setState((){});
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body:Column(
        children: [
          SearchBar(onChange: (String text){
            // print('接收到'+text);
            _searchData(text);
          },),
          Expanded(
            flex: 1,//撑起来，否则，啥都没
            child:MediaQuery.removePadding(context: context,
              //去ListView的掉头
              removeTop: true,
              child: ListView.builder(itemCount: _models.length,
                itemBuilder: _buildCellForRow),),
          ),
        ],
      )
    );
  }

  Widget _buildCellForRow(BuildContext context,int index){
    Chat data = _models[index];
    return ListTile(title: _title(data.name),subtitle: Text(data.message,overflow: TextOverflow.ellipsis,),
        leading: Container(width: 44,height: 44,
          decoration: BoxDecoration(borderRadius: BorderRadius.circular(6.0),
              image: DecorationImage(image: NetworkImage(data.imageUrl))),
        ));
  }
}
